package com.yuanluludev.pgy.update

import android.annotation.SuppressLint
import android.content.Intent
import android.text.TextUtils
import android.text.method.ScrollingMovementMethod
import android.view.View
import com.pgyer.pgyersdk.model.CheckSoftModel
import com.yuanluludev.lib_base.application.BaseApplication
import com.yuanluludev.lib_base.base.BaseVMDialogFragment
import com.yuanluludev.lib_base.ext.toastFailedMiddle
import com.yuanluludev.lib_utils.util.AppUtils
import com.yuanluludev.lib_utils.util.ServiceUtils
import com.yuanluludev.pgy.DownloadService
import com.yuanluludev.pgy.DownloadService.Companion.DOWNLOAD_URL
import com.yuanluludev.pgy.R
import com.yuanluludev.pgy.update.PgyUpdateViewModel.Companion.DOWNLOAD_FAILED
import kotlinx.android.synthetic.main.pgy_update_dialog.*
import java.text.MessageFormat

/**
 * yuanLuLu
 * 有新版本的弹窗
 */
class PgyUpdateDialog(
    private var checkSoftModel: CheckSoftModel,
    private var isBackgroundDownload: Boolean
) :
    BaseVMDialogFragment<PgyUpdateViewModel>() {

    companion object {
        fun newInstance(
            checkSoftModel: CheckSoftModel,
            isBackgroundDownload: Boolean
        ) =
            PgyUpdateDialog(checkSoftModel, isBackgroundDownload)
    }

    @SuppressLint("SetTextI18n")
    override fun initEvents() {

        //需要强制更新
        if (checkSoftModel.isNeedForceUpdate) {
            tvCancel?.visibility = View.GONE
            vDivider?.visibility = View.GONE
        } else {
            tvCancel?.visibility = View.VISIBLE
            vDivider?.visibility = View.VISIBLE
        }

        tvVersionName?.text = checkSoftModel.buildVersion
        tvUpdateInfo?.text = checkSoftModel.buildUpdateDescription
        // 让 TextView 支持滚动
        tvUpdateInfo?.movementMethod = ScrollingMovementMethod.getInstance()
        if (isBackgroundDownload) {
            tvTip?.visibility = View.VISIBLE
        } else {
            tvTip?.visibility = View.GONE
        }
        tvConfirm?.isEnabled = true

        tvCancel?.setOnClickListener {
            dismiss()
        }

        tvConfirm?.setOnClickListener {
            tvConfirm?.isEnabled = false
            tvCancel?.visibility = View.GONE
            tvConfirm?.text = MessageFormat.format("{0}%", "0")

            //后台下载启动service
            if (isBackgroundDownload) {
                dismiss()
                if (!ServiceUtils.isServiceRunning(DownloadService::class.java)) {
                    BaseApplication.getThisApplication().startService(
                        Intent(
                            BaseApplication.getThisApplication(),
                            DownloadService::class.java
                        ).apply {
                            putExtra(DOWNLOAD_URL, checkSoftModel.downloadURL)
                        })
                }
            } else {
                //直接下载
                startDownload()
            }
        }

    }

    private fun startDownload() {
        if (!TextUtils.isEmpty(checkSoftModel.downloadURL)) {
            mViewModel.downloadAPK(checkSoftModel)
        } else {
            "暂无下载地址，下载失败".toastFailedMiddle()
            dismiss()
        }
    }

    override fun observe() {

        mViewModel.run {
            isDismissDownloadDialog.observe(this@PgyUpdateDialog) {
                if (it) dismiss()
            }

            apkPath.observe(this@PgyUpdateDialog) {
                if (!TextUtils.isEmpty(it)) AppUtils.installApp(it)
            }

            downloadProgress.observe(this@PgyUpdateDialog) {
                tvConfirm?.text = MessageFormat.format("{0}%", it.toString())
            }

            //下载失败  Software caused connection abort
            errorResultTip.observe(this@PgyUpdateDialog) {
                if (it.state == DOWNLOAD_FAILED) {
                    it.tipMessage.toastFailedMiddle()
                    dismiss()
                }
            }

        }
    }

    override fun viewModelClass() = PgyUpdateViewModel::class.java

    override fun getLayoutResId() = R.layout.pgy_update_dialog

}